package com.msh.starter.email.instance;

import com.msh.frame.client.exception.BizException;
import com.msh.frame.interfaces.ISendEmail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.beans.factory.annotation.Value;

import java.nio.charset.StandardCharsets;

@Slf4j
public class SimpleEmailSend implements ISendEmail {
  @Value("${msh.starter.email.host:smtphz.qiye.163.com}")
  private String host;
  @Value("${msh.starter.email.port:465}")
  private Integer port;
  @Value("${msh.starter.email.userName:qding@qding.me}")
  private String userName;
  @Value("${msh.starter.email.password:Qd@2014}")
  private String password;
  @Value("${msh.starter.email.fromUser:qding@qding.me}")
  private String fromUser;

  @Override
  public void simpleEmail(String to, String title, String content) {
    try {
      SimpleEmail simpleEmail = buildSampleEmail();
      simpleEmail.setSubject(title);
      simpleEmail.setMsg(content);
      simpleEmail.addTo(to);
      simpleEmail.send();
    } catch (EmailException e) {
      log.error("发送邮件失败.", e);
      throw new BizException("发送邮件失败");
    }
  }

  public SimpleEmail buildSampleEmail() throws EmailException {
    SimpleEmail simpleEmail = new SimpleEmail();
    simpleEmail.setHostName(host);
    simpleEmail.setSmtpPort(port);
    simpleEmail.setAuthenticator(new DefaultAuthenticator(userName, password));
    simpleEmail.setSSLOnConnect(true);
    simpleEmail.setFrom(fromUser);
    simpleEmail.setCharset(StandardCharsets.UTF_8.name());
    return simpleEmail;
  }
}
